package com.ganxiang.ximenhong.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewParent;
import android.view.inputmethod.InputMethodManager;

import com.ganxiang.ximenhong.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

public class Utils {
	
	public static String getPackNmae(Context c) {
		String pkName = "";
		try {
			pkName = c.getPackageName();
		} catch (Exception e) {
		}
		return pkName;
	}
	
    public static int dipToPixels(Context context, float dip){
		return (int)(context.getResources().getDisplayMetrics().density * dip);
	}
    
	public static int realHeight(Context context, int scaleHeight){
		return (int) (context.getResources().getDisplayMetrics().widthPixels / ((double)640 / (double)scaleHeight));
	}
	
	public static String getClientInfo(Context context){
		return android.os.Build.MODEL + "|android|" +android.os.Build.VERSION.RELEASE + "|" + getVersionName(context) + "|" + getVersionNumber(context) + "|" + context.getResources().getDisplayMetrics().widthPixels + "*" + context.getResources().getDisplayMetrics().heightPixels +"|" + context.getResources().getDisplayMetrics().densityDpi;
	}
	
	public static void removeSoftKeyboard(Activity activity){
		 InputMethodManager imm =(InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		 if(activity.getCurrentFocus() != null)
			imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); 
	 }
	
	public static String DecimalFormat(String formatStr, int num){
		String str = "";
		if(formatStr == null){
			return formatStr;
		}
		
		String d = "";
		if(num > 0){
			for(int i = 0; i < num; i ++){
				d += "0";
			}
			DecimalFormat df = new DecimalFormat("######0." + d); 
			try {
				double d1 = Double.parseDouble(formatStr);  
				str = df.format(d1);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}else {
			str = formatStr.split(".")[0];
		}
		
		return str;
	}
	
	public static JSONArray jsonArrayParser(InputStream inputStream){
		JSONArray dataArray = null;
		BufferedReader bufferReader = null;
		String line = null;
		StringBuffer sb = new StringBuffer();
		try {
			bufferReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while((line = bufferReader.readLine()) != null){
				sb.append(line);
			}
			dataArray = new JSONArray(sb.toString());
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return dataArray;
	}
	
	public static boolean isTextEmpty(String text){
		if(TextUtils.isEmpty(text) || text.replaceAll(" ", "").length() == 0){
			return true;
		}
		return false;
	}
	
	public static String urlEncode(String url, String encode){
		String str = null;		
		try {
			 str = URLEncoder.encode(url, encode);
			 /*这个item.getLink()是得到请求的具体网络路径�?? 而下面replaceAll函数是在String里面转译字符�??
			 这个是对网络路径上用GBK转码�??/）后斜杠�??%2F来表示，冒号（：）用%3A来表�?? ，加号（+）用%20来表�??
			 ，加号是java中特殊符号，�??以用正则表达式双斜杠�??//）�?�下面这个转码的意�?�是指在取用GBK转码后，GBK把斜杠和冒号，加号等特殊符号都给转译了，
			 �??以才要做此操作�?�我这是正对解析视频文件而做的，大部分的只需上面写到的str = java.net.URLEncoder.encode(item.getLink(),"GBK");就可�??*/
			 str = str.replaceAll("%2F","/");
			 str = str.replaceAll("%3A",":");
			 str = str.replaceAll("\\+","%20");
			 str = str.replaceAll("%3D","=");
			 str = str.replaceAll("%26","&");
			 str = str.replaceAll("%3F","?");
			 str = str.replaceAll("%23","#");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	 }
	
	/**
	 * @param originalBase64 被转�??+的base64
	 * @return
	 */
	public static String transformBase64(String originalBase64){
		if(originalBase64 == null || originalBase64.length() == 0){
			return "";
		}
		
		try {
			return URLEncoder.encode(originalBase64, "utf-8");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";
	}
	
	@SuppressWarnings("unchecked")
	public static void removeIndex(JSONArray arr, int index){
		if(index < 0)
			return;
		try {
			Field valuesField=JSONArray.class.getDeclaredField("values");
			valuesField.setAccessible(true);
			List<Object> values=(List<Object>)valuesField.get(arr);
			if(index >= values.size()){
				return;
			}
			values.remove(index);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static String[] getPicResolution(String url){
		if(url == null || url.length() == 0 || !url.contains("_") || !url.contains(".") || !url.contains("x")){
			return null;
		}
		try {
			return url.substring(url.lastIndexOf("_") + 1).split("\\.")[0].split("x");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
	public static void destoryBimap(Bitmap photo) {
		if (photo !=null && !photo.isRecycled()) {
			photo.recycle();
			photo = null;
		}
	}

	public static boolean isMobileNO(String mobiles) {
		String telRegex = "[1][358]\\d{9}";
		if (TextUtils.isEmpty(mobiles)) {
			return false;
		}
		return mobiles.matches(telRegex);
    }
	
	/**
	 * bitmap转为base64
	 * @param bitmap
	 * @return
	 */
	public static String bitmapToBase64(Bitmap bitmap) {
		String result = null;
		ByteArrayOutputStream baos = null;
		try {
			if (bitmap != null) {
				baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				result = Utils.transformBase64(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT));
				//Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	public static Bitmap revitionImageSize(String path){
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(new File(path)));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(in == null){
			return null;
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(in, null, options);
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int i = 0;
		Bitmap bitmap = null;
		while (true) {
			if ((options.outWidth >> i <= 2000) && (options.outHeight >> i <= 2000)) {
				try {
					in = new BufferedInputStream(new FileInputStream(new File(path)));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				options.inSampleSize = (int) Math.pow(2.0D, i);
				options.inJustDecodeBounds = false;
				bitmap = BitmapFactory.decodeStream(in, null, options);
				Matrix m = new Matrix();  
                int width = bitmap.getWidth();  
                int height = bitmap.getHeight();  
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();  
				bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
				break;
			}
			i += 1;
		}
		return bitmap;
	}
	
	/**
	 * in: yyyy-MM-dd HH:mm:ss
	 * out:
	 *     MM月dd�?? HH:mm am/pm
	 *     N小時�??
	 *     N分鐘�??
	 *     剛剛
	 *     昨天
	 *     前天  
	 * @param context
	 * @param timeStr
	 * @return
	 */
	public static String formatTime(Context context, String timeStr){
		if(timeStr == null || timeStr.equalsIgnoreCase("")){
			return "";
		}
		
		int cuYear = Calendar.getInstance().get(Calendar.YEAR);
		int cuMonth = Calendar.getInstance().get(Calendar.MONTH);
		int cuDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		int cuHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
		int cuMinute = Calendar.getInstance().get(Calendar.MINUTE);
		
		Date date = null;
		try {
			date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(timeStr);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if(date == null){
			return "";
		}
		
		if((date.getYear() + 1900) == cuYear && date.getMonth() == cuMonth){
			if(cuDay == date.getDate()){
				if(cuHour == date.getHours()){
					if(cuMinute == date.getMinutes()){
						return context.getString(R.string.time_now);
					}else{
						return (cuMinute - date.getMinutes()) + context.getString(R.string.time_minute);
					}
				}else{
					return (cuHour - date.getHours()) + context.getString(R.string.time_hour);
				}
			}else {
				if (cuDay - 1 == date.getDate()) {
					if (cuHour + (24 - date.getHours()) < 24)
						return (cuHour + (24 - date.getHours())) + context.getString(R.string.time_hour);
					return context.getString(R.string.time_yestoday);


				} else {
					if (cuDay - 2 == date.getDate()) {
						return context.getString(R.string.time_beforeyestoday);
					}
				}
			}
		}
		
		return new SimpleDateFormat(context.getString(R.string.time_mdhm)).format(date);
	}
    
   public static String getDiaryDate(){
	   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	   return format.format(new Date());
   }
    
    public static Date toDate(String sdate) {
        try {
            return dateFormater2.get().parse(sdate);
        }
        catch (ParseException e) {
            return null;
        }
    }
    
    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            //return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return new SimpleDateFormat("yyyyMMddHHmmssSSS");
        }
    };
    
    public static long getTotalTime(){
    	SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    	return Long.parseLong(format.format(new Date()));
    }
	
	 public static boolean isInternetAvaiable(Context context){
        ConnectivityManager mannager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info=mannager.getActiveNetworkInfo();
        if(info==null || !info.isAvailable() || !info.isConnected()){
            return false;
        }
        
        return true;
	 }  
	
	 public static int getVersionNumber(Context context){
		String packageName = context.getPackageName();
		int version = 0;
		try {
		    PackageInfo pinfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_CONFIGURATIONS);
		    version = pinfo.versionCode;
		} 
		catch (NameNotFoundException e) {
			e.printStackTrace();
		}	
		return version;
	}
	 
	 public static String getVersionName(Context context){
		String packageName = context.getPackageName();
		String versionName = null;
		try {
		    PackageInfo pinfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_CONFIGURATIONS);
		    versionName = pinfo.versionName;
		} 
		catch (NameNotFoundException e) {
			e.printStackTrace();
		}	
		return versionName;
	}
	 
	@SuppressWarnings("deprecation")
	public static int getAndroidSDKVersion() { 
	   int version = 0; 
	   try { 
	     version = Integer.valueOf(android.os.Build.VERSION.SDK); 
	   } catch (NumberFormatException e) { 
		   e.printStackTrace();
	   } 
	   return version; 
	} 
	
	public static String getAndroidSDKVersionName() { 
	   String version = ""; 
	   try { 
	     version = android.os.Build.VERSION.RELEASE; 
	   } catch (NumberFormatException e) { 
		   e.printStackTrace();
	   } 
	   return version; 
	} 
	
	public static String getLocalIpAddress() {  
         String ipaddress="";
         
	     try {  
	         for (Enumeration<NetworkInterface> en = NetworkInterface  
	                 .getNetworkInterfaces(); en.hasMoreElements();) {  
	             NetworkInterface intf = en.nextElement();  
	             for (Enumeration<InetAddress> enumIpAddr = intf  
	                     .getInetAddresses(); enumIpAddr.hasMoreElements();) {  
	                 InetAddress inetAddress = enumIpAddr.nextElement();  
	                 if (!inetAddress.isLoopbackAddress()) {  
	                         ipaddress=ipaddress+";"+ inetAddress.getHostAddress().toString();  
	                 }  
	             }  
	         }  
	     } catch (SocketException ex) {  
	     }  
	     int index = 0;
	     if(ipaddress != null && ((index = ipaddress.lastIndexOf(";")) != -1)){
	    	 ipaddress = ipaddress.substring(index + 1);
	     }
	     return ipaddress; 
     }

	 public boolean isWiFiAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (null != cm) {
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
						info = null;
						return true;
					}
				}
			}
			info = null;
		}
		return false;
	}
	 
	 public static String getHardwareID(Context context) {
		if (null == context) return null;

		String strId = null;
		
		// 取IMEI，需要有电话模块
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		if (null != tm) strId = tm.getDeviceId();
		if (null != strId && strId.length()>5) {
				
			// 有IMEI
			return "i." + strId;
		}
		
		// 硬件serialno�?? �??�??2.3才支�??
		try {
			
			Class<?> c = Class.forName("android.os.SystemProperties");
			Method get = c.getMethod("get", String.class, String.class);
			strId = (String) (get.invoke(c, "ril.serialnumber", "none"));
			if (null == strId || strId.length() < 8)
				strId = (String) (get.invoke(c, "ro.serialno", "none"));
			if (null != strId && strId.length() > 7) return "s." + strId;
		} 
		catch (Exception ignored) {}
		
		// 取wifi mac
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (null != wifi){
		
			WifiInfo info = wifi.getConnectionInfo();
			if (null != info) strId = info.getMacAddress();	
			if (null != strId && strId.length()>8) return "m." + strId;
		}
		
		// 硬件serialno�?? �??�??2.2才能真正支持
		strId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);		
		if (null != strId && strId.length()>8) return "a." + strId;
		
		return strId;
	}
	 
	 public static View getParentView(Class<?> cls, View v){
		 ViewParent parent = v.getParent();
		if((parent instanceof View)){
			if(parent.getClass() == cls){
				return (View) parent;
			}
			else{
				return getParentView(cls, (View) parent);
			}
		}
		return null;
	}
	
	 public static void changeLanguage(Context context, int lan){			
		Configuration config = context.getResources().getConfiguration(); 
		DisplayMetrics dm = context.getResources() .getDisplayMetrics(); 
		config.locale = lan == 0 ? Locale.TRADITIONAL_CHINESE : Locale.SIMPLIFIED_CHINESE; 
		context.getResources().updateConfiguration(config, dm); 
	 }
	 
	 public static void installApk(Context context, File file){
		if(file.exists()){
			Intent intent = new Intent();
		    intent.setAction(Intent.ACTION_VIEW);
		    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		    context.startActivity(intent);
		}
	}
	 
	 
	public static String getNaturalTime(String timeStr) {
		String time = "";
		Date date = null;

		try {
			date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(timeStr);
			SimpleDateFormat format = new SimpleDateFormat("h:mm");
            if(date.getHours() < 12){
            	time =  format.format(date)+ " AM";
            }else {
            	time =  format.format(date)+ " PM";
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return time;
	}
	 
	 
	 public static JSONObject getJsonFromInputStream(InputStream inputStream){
			JSONObject dataJson = null;
			BufferedReader bufferReader = null;
			String line = null;
			StringBuffer sb = new StringBuffer();
			try {
				bufferReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
				while((line = bufferReader.readLine()) != null){
					sb.append(line);
				}
				String str_json = sb.toString();
			    if (str_json != null && str_json.startsWith("\ufeff")) {  
			    	str_json = str_json.substring(1);  
			         }  
				dataJson = new JSONObject(str_json);
			}catch (Exception e) {
				e.printStackTrace();
			}
			return dataJson;
		}
		 
	 public static String decodeUnicode(String theString) { 
	        char aChar; 
	        int len = theString.length(); 
	        StringBuffer outBuffer = new StringBuffer(len); 
	        for (int x = 0; x < len;) { 
	            aChar = theString.charAt(x++); 
	            if (aChar == '\\') { 
	                aChar = theString.charAt(x++); 
	                if (aChar == 'u') { 
	                    // Read the xxxx 
	                    int value = 0; 
	                    for (int i = 0; i < 4; i++) { 
	                        aChar = theString.charAt(x++); 
	                        switch (aChar) { 
	                        case '0': 
	                        case '1': 
	                        case '2': 
	                        case '3': 
	                        case '4': 
	                        case '5': 
	                        case '6': 
	                        case '7': 
	                        case '8': 
	                        case '9': 
	                            value = (value << 4) + aChar - '0'; 
	                            break; 
	                        case 'a': 
	                        case 'b': 
	                        case 'c': 
	                        case 'd': 
	                        case 'e': 
	                        case 'f': 
	                            value = (value << 4) + 10 + aChar - 'a'; 
	                            break; 
	                        case 'A': 
	                        case 'B': 
	                        case 'C': 
	                        case 'D': 
	                        case 'E': 
	                        case 'F': 
	                            value = (value << 4) + 10 + aChar - 'A'; 
	                            break; 
	                        default: 
	                            throw new IllegalArgumentException( 
	                                    "Malformed   \\uxxxx   encoding."); 
	                        } 
	     
	                    } 
	                    outBuffer.append((char) value); 
	                } else { 
	                    if (aChar == 't') 
	                        aChar = '\t'; 
	                    else if (aChar == 'r') 
	                        aChar = '\r'; 
	                    else if (aChar == 'n') 
	                        aChar = '\n'; 
	                    else if (aChar == 'f') 
	                        aChar = '\f'; 
	                    outBuffer.append(aChar); 
	                } 
	            } else 
	                outBuffer.append(aChar); 
	        } 
	        return outBuffer.toString(); 
	    }

	   
	 
	 
		 public static JSONArray getJsonArrayFromInputStream(InputStream inputStream){
			JSONArray dataArray = null;
			BufferedReader bufferReader = null;
			String line = null;
			StringBuffer sb = new StringBuffer();
			try {
				bufferReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
				while((line = bufferReader.readLine()) != null){
					sb.append(line);
				}
				dataArray = new JSONArray(sb.toString());
			}catch (Exception e) {
				e.printStackTrace();
			}
			return dataArray;
		}
		 
		 public static String getFromAssets(Context context,String fileName){ 
		        try { 
		             InputStreamReader inputReader = new InputStreamReader( context.getResources().getAssets().open(fileName) ); 
		            BufferedReader bufReader = new BufferedReader(inputReader);
		            String line="";
		            String Result="";
		            while((line = bufReader.readLine()) != null)
		                Result += line;
		            return Result;
		        } catch (Exception e) { 
		            e.printStackTrace(); 
		        }
		        
		        return "";
		} 
		 
		//星期�??
		public static int getWeekday(int year, int month, int day){
			Calendar cal = Calendar.getInstance();
			cal.set(year, month - 1, day);
			return cal.get(Calendar.DAY_OF_WEEK) - 1;
		}
		
		public static int getWeekday(String date){
			String[] dates = date.split("-");
			Calendar cal = Calendar.getInstance();
			cal.set(Integer.parseInt(dates[0]), Integer.parseInt(dates[1]) - 1, Integer.parseInt(dates[2]));
			return cal.get(Calendar.DAY_OF_WEEK) - 1;
		}
		
		public static JSONObject mergeJSONObject(JSONObject oldOne, JSONObject newOne){
			Iterator<String> it = newOne.keys();
			while (it.hasNext()) {
				String key = it.next();
				try {
					if(oldOne.has(key)){
						oldOne.put(key, newOne.opt(key));
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return oldOne;
		}
		
		//合并jsonarray
		 public static JSONArray joinJSONArray(JSONArray mOld, JSONArray mNew) {
			if(mOld == null && mNew == null){
				return null;
			}
			if(mOld == null){
				return mNew;
			}
			if(mNew == null){
				return mOld;
			}
			StringBuffer buffer = new StringBuffer();
			try {
				int len = mOld.length();
				for (int i = 0; i < len; i++) {
					JSONObject obj1 = (JSONObject) mOld.get(i);
					if (i == len - 1)
						buffer.append(obj1.toString());
					else
						buffer.append(obj1.toString()).append(",");
				}
				len = mNew.length();
				if (len > 0)
					buffer.append(",");
				for (int i = 0; i < len; i++) {
					JSONObject obj1 = (JSONObject) mNew.get(i);
					if (i == len - 1)
						buffer.append(obj1.toString());
					else
						buffer.append(obj1.toString()).append(",");
				}
				buffer.insert(0, "[").append("]");
				return new JSONArray(buffer.toString());
			} catch (Exception e) {
			}
			catch (OutOfMemoryError e) {
				// TODO: handle exception
			}
			return null;
		}
		 
	public static int getStatusHeight(Activity activity) {
		int statusHeight = 0;
		Rect localRect = new Rect();
		activity.getWindow().getDecorView()
				.getWindowVisibleDisplayFrame(localRect);
		statusHeight = localRect.top;
		if (0 == statusHeight) {
			Class<?> localClass;
			try {
				localClass = Class.forName("com.android.internal.R$dimen");
				Object localObject = localClass.newInstance();
				int i5 = Integer.parseInt(localClass
						.getField("status_bar_height").get(localObject)
						.toString());
				statusHeight = activity.getResources()
						.getDimensionPixelSize(i5);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		return statusHeight;
	}
		 
	// 复制文件
	public static void copyFile(File sourceFile, File targetFile)
			throws IOException {
		// 新建文件输入流并对它进行缓冲
		FileInputStream input = new FileInputStream(sourceFile);
		BufferedInputStream inBuff = new BufferedInputStream(input);

		// 新建文件输出流并对它进行缓冲
		FileOutputStream output = new FileOutputStream(targetFile);
		BufferedOutputStream outBuff = new BufferedOutputStream(output);

		// 缓冲数组
		byte[] b = new byte[1024 * 5];
		int len;
		while ((len = inBuff.read(b)) != -1) {
			outBuff.write(b, 0, len);
		}
		// 刷新此缓冲的输出�??
		outBuff.flush();

		// 关闭�??
		inBuff.close();
		outBuff.close();
		output.close();
		input.close();
	}


	/**
	 * 随机指定范围内N个不重复的数 �??�??单最基本的方�??
	 * 
	 * @param min
	 *            指定范围�??小�??
	 * @param max
	 *            指定范围�??大�??
	 * @param n
	 *            随机数个�??
	 */  
	public static int[] randomCommon(int min, int max, int n) {
		if (n > (max - min + 1) || max < min) {
			return null;
		}
		int[] result = new int[n];
		int count = 0;
		while (count < n) {
			int num = (int) (Math.random() * (max - min)) + min;
			boolean flag = true;
			for (int j = 0; j < n; j++) {
				if (num == result[j]) {
					flag = false;
					break;
				}
			}
			if (flag) {
				result[count] = num;
				count++;
			}
		}
		return result;
	}
	
	/**
	 * 根据路径删除本地目录及里面的文件
	 * @param path
	 * @return
	 */
    public static boolean deleteDir(String path){
        boolean success = true ;
        File file = new File(path) ;
        if(file.exists()){
            File[] list = file.listFiles() ;
            if(list != null){
                int len = list.length ;
                for(int i = 0 ; i < len ; ++i){
                    if(list[i].isDirectory()){
                        deleteDir(list[i].getPath()) ;
                    }
                    else {
                        boolean ret = list[i].delete() ;
                        if(!ret){
                            success = false ;
                        }
                    }
                }
            }
        }
        else{
            success = false ;
        }
        if(success){
            file.delete() ;
        }
        return success ;
    }
    public static String friendlyTime(Context context, long timeMills) {
		if (timeMills == 0) {
			return "unknown";
		}

		Calendar cal = Calendar.getInstance();
		long getTimeInMillis = cal.getTimeInMillis();

		long t1 = getTimeInMillis / 1000;
		long t2 = timeMills / 1000;
		int distance = (int) (t1 - t2);
		if (distance < 60) {
			return context.getResources().getString(R.string.time_now);
		}

		String ftime = "";

		long lt = timeMills / 86400000;
		long ct = getTimeInMillis / 86400000;
		int days = (int) (ct - lt);
		if (days == 0) {
			int hour = (int) ((getTimeInMillis - timeMills) / 3600000);
			if (hour == 0)
				ftime = Math.max((getTimeInMillis - timeMills) / 60000, 1)
						+ context.getResources()
								.getString(R.string.time_minute);
			else
				ftime = hour
						+ context.getResources().getString(R.string.time_hour);
		} else if (days == 1) {
			ftime = context.getResources().getString(R.string.time_yestoday);
		} else if (days == 2) {
			ftime = context.getResources().getString(
					R.string.time_beforeyestoday);
		} else {
			SimpleDateFormat YMDHMformat = new SimpleDateFormat("yyyy-MM-dd H:m");
			ftime = YMDHMformat.format(new Date(timeMills));
		}
		return ftime;
	}
}
